<template>
  <div class="box">
    <header class="header">
      <van-nav-bar
        title="购物车"
        left-arrow
        @click-left="$router.push('/home')"
      />
    </header>
    <div class="content cart">
      <van-empty description="购物车空空如也" v-if="flag">
        <van-button round type="danger" class="bottom-button" @click="$router.push('/home')">
          去逛一逛
        </van-button>
      </van-empty>
      <div v-else>
          <van-swipe-cell v-for="(item, idx) in cartList" :key="item.proId">
            <van-card
             :price="item.price"
             :desc="item.taste"
             :title="item.proName"
            >
            <template #thumb>
              <van-checkbox v-model="item.flag" @click="selFlag(idx)"></van-checkbox>
                <van-image :src="item.proImg" fit="cover" />
              </template>
            <template #num>
                <van-stepper v-model="item.num" theme="round" button-size="22" @change="change" :name="item.proId"/>
            </template>
            </van-card>
            <template #right>
              <van-button square text="删除" type="danger" class="delete-button" @click="del(item.proId, idx)"/>
            </template>
          </van-swipe-cell>
          <van-submit-bar :price="priceSum*100" button-text="结算" @submit="onSubmit">
            <van-checkbox v-model="allSleFlag">全选</van-checkbox>
            <template #tip>
              您选择了<span>{{proSum}}</span>件商品
            </template>
          </van-submit-bar>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import Cookies from 'js-cookie'
import { Card, Empty, Button, Stepper, SwipeCell, Image as VanImage, Checkbox, SubmitBar, NavBar, Toast } from 'vant'
import { getCart, getDetail, updateNum, delCart, updateFlag, updateAllFlag, addOrder } from '../../api/index.js'

Vue.use(Card)
Vue.use(Button)
Vue.use(Empty)
Vue.use(Stepper)
Vue.use(SwipeCell)
Vue.use(VanImage)
Vue.use(Checkbox)
Vue.use(SubmitBar)
Vue.use(NavBar)
Vue.use(Toast)
export default {
  // 组件路由守卫
  beforeRouteEnter (to, from, next) {
    if (Cookies.get('isLogin') === 'ok') {
      // 需求 如果登陆则返回上一级路由
      // 参数to.path存储的有上级路由
      next()
    } else {
      next('/login?to=' + to.path)
    }
  },
  data () {
    return {
      cartList: []
    }
  },
  methods: {
    // 修改数量
    change (value, detail) {
      console.log(detail.name)
      updateNum({
        userId: Cookies.get('userId'),
        proId: detail.name,
        num: value
      }).then(res => {
        // 商品数量修改成功之后的回调函数
        // console.log(res.data)
      })
    },
    // 删除商品
    del (id, i) {
      delCart({
        userId: Cookies.get('userId'),
        proId: id
      }).then(res => {
        // 删除成功之后立马将cartList内的数据一并删除
        this.cartList.splice(i, 1)
      })
    },
    // 提交订单
    onSubmit () {
      const arr = this.cartList.filter(val => {
        // 使用数据过滤 当状态为选中的情况下将数据返回出去
        return val.flag
      })
      // 将数据中用不到的数据去掉
      // 定义一个新数组
      const arr2 = []
      // 使用结构
      arr.forEach(val => {
        arr2.push({
          num: val.num,
          price: val.price,
          proName: val.proName,
          proImg: val.proImg,
          time: val.time,
          proId: val.proId,
          flag: val.flag
        })
      })
      console.log(arr2, 333)
      // 添加至订单
      addOrder({
        userId: Cookies.get('userId'),
        proData: arr2
      }).then(res => {
        // 成功之后
        console.log('数据添加成功')
        this.$router.push('/order')
      })
    },
    selFlag (i) {
      // console.log(this.cartList[i].proId, this.cartList[i].flag)
      updateFlag({
        userId: Cookies.get('userId'),
        proId: this.cartList[i].proId,
        flag: this.cartList[i].flag
      }).then(() => {
      })
    }
  },
  computed: {
    flag () {
      return this.cartList.length < 1
    },
    proSum () {
      return this.cartList.reduce((prev, next) => {
        // 减去零是为了确保num是一个数字类型的数据
        // return prev + (next.num - 0)
        return next.flag ? prev + (next.num - 0) : prev
        // reduce的第二个参数是prev的初始值
      }, 0)
    },
    priceSum () {
      return this.cartList.reduce((prev, next) => {
        // return prev + (next.num - 0) * next.price
        return next.flag ? prev + (next.num - 0) * next.price : prev
      }, 0)
    },
    allSleFlag: {
      get () {
        return this.cartList.every(val => {
          // val.flag本身就为布尔值 只有当所有都为true返回结果才为true
          return val.flag
        })
      },
      set (val) {
        // 采用for循环 需要操作原数组
        for (let i = 0; i < this.cartList.length; i++) {
          this.cartList[i].flag = val
        }
        // 点击全选的时候改变数据库中的状态
        updateAllFlag({
          userId: Cookies.get('userId'),
          flag: val
        }).then(res => {
          console.log('状态更新成功')
        })
      }
    }
  },
  // 和生命周期钩子函数和计算函数和的
  mounted () {
    getCart({
      userId: Cookies.get('userId')
    }).then(res => {
      if (Cookies.get('num')) {
        Cookies.set('num', res.data.data.proData.length)
      }
      // 获取到后台的数据 不要直接操作数据库 另行保存出来
      const arr = res.data.data.proData
      console.log(arr)
      // 知道商品id要去后台请求购物车数据库中去请求数据
      arr.forEach(val => {
        getDetail({
          id: val.proId
        }).then(data => {
          const obj = data.data.data
          obj.num = val.num
          obj.time = val.time + ''
          // 将商品选中状态放入到对象中去
          obj.flag = val.flag
          this.cartList.push(obj)
          console.log(this.cartList)
        })
      })
    })
  }
}
</script>

<style lang="scss">
.header {
  .van-icon{
    font-size: 24px;
  }
}

.cart{
  .bottom-button{
    width: 1rem;
    border-radius: 0.1rem;
    background-color: #02d4d7;
    border: none;
    font-size: 0.16rem;
  }
  .van-image__img{
    margin-left: -10px;
  }
  .delete-button{
      height: 100%;
  }
  .van-card__thumb{
      display: flex;
      width:1.3rem;
      img{
        width:88px
  }
  .van-checkbox{
      margin-right:0.1rem
      }
    }
    .van-submit-bar__button--danger{
      background-color: #02d4d7;
      color: #fff;
      border-radius: 0.1rem;
      width: 0.8rem;
      font-size: 0.18rem;
    }
    .van-submit-bar__tip{
        span{
          font-size: 20px;
          line-height: 20px;
          margin: 0 3px;
        }
    }
  }
</style>
